﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using x1.Framework;
using System.IO;
public class ResManager : UnitySingleton<ResManager> {

    [HideInInspector]
    public string resPath = "";//Application.dataPath + "/GResources";
    [HideInInspector]
    public string outPath = "";//Application.streamingAssetsPath + "/";


    //服务端资源文件信息
    private Dictionary<string, string> serverFile = new Dictionary<string, string>();
    //本地资源文件信息
    private Dictionary<string, string> localFile = new Dictionary<string, string>();
    //需要下载的lua文件
    private List<string> luaFiles = new List<string>();
    //需要下载的assetbundle文件
    private List<string> abFiles = new List<string>();

    //private  LoadAsset _type;

    private IGAssetLoader assetLoader;

    public override void Init()
    {
        
    }

    //    public void Init(LoadAsset type)
    //    {
    //        resPath = Application.dataPath + "/GResources";
    //        outPath = Application.streamingAssetsPath + "/";
    //#if UNITY_EDITOR
    //        _type = type;
    //        if (type == LoadAsset.AssetBundle)
    //        {
    //            assetLoader = new GABLoader();
    //        }
    //        else if (type == LoadAsset.Editor)
    //        {
    //            assetLoader = new GEditorLoader();
    //        }
    //        else
    //        {
    //            assetLoader = new GABLoader();
    //        }
    //        //#elif !UNITY_EDITOR 
    //        //        assetLoader = new GABLoader();
    //#else
    //        assetLoader = new GABLoader();
    //        _type = LoadAsset.AssetBundle;
    //#endif
    //    }

    /// <summary>
    /// 同步获取资源
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public T GetRes<T>(string path) where T : Object
    {
        return assetLoader.GetRes<T>(path);
    }

    public Object GetRes(string path)
    {
        return assetLoader.GetRes(path);
    }

    /// <summary>
    /// 异步获取资源
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <param name="callback"></param>
    public void GetResAsync<T>(string path, System.Action<string, T> callback) where T : Object
    {
        assetLoader.GetResAsync<T>(path, callback);
    }

    public void GetResAsync(string path,System.Action<string,Object> callback)
    {
        assetLoader.GetResAsync(path, callback);
    }

    /// <summary>
    /// 检查资源
    /// </summary>
    public void CheckRes()
    {
        CheckLuaVersion();
    }

    public void LoadRes(string path, System.Action<WWW> callback)
    {
        StartCoroutine(_LoadRes(path, callback));
    }

    private IEnumerator _LoadRes(string path, System.Action<WWW> callback)
    {
        WWW www = new WWW("file://" + path);

        yield return www;

        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError("资源加载失败:" + path + "\n res:" + www.error);
            if (callback != null)
                callback(null);
        }
        else
        {
            if (callback != null)
            {
                callback(www);
            }
        }
    }


    /// <summary>
    /// 检查lua版本
    /// </summary>
    private void CheckLuaVersion()
    {
        DownLoadVersion(AppConfig.LUA_RES_SERVICE_VERSION, ApplicationPlatform.GetPersistentDataPath(AppConfig.LUA_RES_LOCAL_VERSION) , DownLoadLuaFile);
    }

    /// <summary>
    /// 检查AssetBundle版本
    /// </summary>
    private void CheckAssetBundleVersion()
    {
        DownLoadVersion(AppConfig.AB_RES_SERVICE_VERSION, ApplicationPlatform.GetPersistentDataPath(AppConfig.AB_RES_LOCAL_VERSION) , DownLoadAssetBundleFie);
    }

    /// <summary>
    /// 下载lua文件
    /// </summary>
    private void DownLoadLuaFile()
    {
        if (serverFile.Count > 0 && localFile.Count > 0)
        {
            foreach (var key in serverFile.Keys)
            {
                if (localFile.ContainsKey(key))
                {
                    if (localFile[key] != serverFile[key])
                    {
                        luaFiles.Add(key);
                    }
                }
                else
                {
                    luaFiles.Add(key);
                }
            }
            serverFile.Clear();
            localFile.Clear();
            //LoadingView.instance.StartDownLoad(luaFiles.Count);
        }

        if (luaFiles.Count > 0)
        {
            DownLoadFile(AppConfig.LUA_RES_SERVICE, AppConfig.LUA_RES_LOCAL, luaFiles[0], DownLoadLuaFile);
        }
        else
        {
            //更换版本文件
            string oldFile = AppConfig.LUA_RES_LOCAL_VERSION;
            string newFile = AppConfig.LUA_RES_SERVICE_VERSION;
            DownLoadManager.DownLoad(newFile, (www) =>
            {
                IO.DeleteFiles(oldFile);
                //Loger.Info("--->>oldFile" + oldFile);
                CreateFile(www.bytes, oldFile);
                CheckAssetBundleVersion();
            });
        }
    }

    /// <summary>
    /// 下载assetbundle文件
    /// </summary>
    private void DownLoadAssetBundleFie()
    {
        if (serverFile.Count > 0 && localFile.Count > 0)
        {
            foreach (var key in serverFile.Keys)
            {
                if (localFile.ContainsKey(key))
                {
                    if (localFile[key] != serverFile[key])
                    {
                        luaFiles.Add(key);
                    }
                }
                else
                {
                    luaFiles.Add(key);
                }
            }
            serverFile.Clear();
            localFile.Clear();
            //LoadingView.instance.StartDownLoad(luaFiles.Count);
        }

        if (luaFiles.Count > 0)
        {
            DownLoadFile(AppConfig.AB_RES_SERVICE, AppConfig.AB_RES_LOCAL, luaFiles[0], DownLoadAssetBundleFie);
        }
        else
        {
            //更换版本文件
            string oldFile = AppConfig.AB_RES_LOCAL_VERSION;
            string newFile = AppConfig.AB_RES_SERVICE_VERSION;
            DownLoadManager.DownLoad(newFile, (www) =>
            {
                IO.DeleteFiles(oldFile);
                //Loger.Info("--->>oldFile" + oldFile);
                CreateFile(www.bytes, oldFile);
                //CheckAssetBundleVersion();
                //进入游戏
                //LoadingView.instance.LoadEnd();
            });
        }
    }

    /// <summary>
    /// 下载版本文件
    /// </summary>
    /// <param name="servicePath"></param>
    /// <param name="localPath"></param>
    /// <param name="callBack"></param>
    private void DownLoadVersion(string servicePath,string localPath,System.Action callBack)
    {
        DownLoadManager.DownLoad(servicePath, (www) =>
        {
            //Debug.Log("version:" + www.text);
            string[] strs = www.text.Split('\n');
            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;
                string[] file = str.Split('|');
                if (file.Length == 3)
                    serverFile.Add(file[0], file[1]);
            }
            //downLoaNum++;
            //Debug.Log("---------------------------------------");
            //LoadLcalFile(localPath);
            //callBack();
            LoadLocalFile(localPath, callBack);
        });
    }



    /// <summary>
    /// 下载文件
    /// </summary>
    private void DownLoadFile(string serverPath, string localPath, string fielName, System.Action callBack = null)
    {
        //loadView.ShowLoadText(fielName);

        DownLoadManager.DownLoad(serverPath + fielName, (www) =>
        {
            byte[] bytes = www.bytes;
            CreateFile(bytes, localPath + "/" +fielName);
            //LoadingView.instance.UpdateProgress();
            if (luaFiles.Count != 0 || abFiles.Count != 0)
            {
                if (luaFiles.Count > 0)
                    luaFiles.RemoveAt(0);
                if (abFiles.Count > 0)
                    abFiles.RemoveAt(0);
                if (callBack != null)
                    callBack();
            }
        });
    }

    /// <summary>
    /// 加载本地文件
    /// </summary>
    /// <param name="path"></param>
    /// <param name="callBack"></param>
    private void LoadLocalFile(string path, System.Action callBack)
    {
        DownLoadManager.DownLoad(path, (www) =>
        {
            string[] strs = www.text.Split('\n');
            foreach (var str in strs)
            {
                if (string.IsNullOrEmpty(str))
                    continue;
                string[] file = str.Split('|');
                localFile.Add(file[0], file[1]);
            }
            callBack();
        });
       
    }


    /// <summary>
    /// 创建文件
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="savePath"></param>
    private void CreateFile(byte[] bytes, string savePath)
    {
        string path = Application.persistentDataPath + "/Res";
        string[] strs = savePath.Split('/');
        if (strs.Length > 0)
        {
            string dir = savePath.Substring(0, savePath.Length - strs[strs.Length - 1].Length);
            //dir = path + dir;
            //Debug.Log("dir:" + dir);
            if (!Directory.Exists(dir))
            {
                //如果不存在该目录，则创建该目录
                Debug.Log("dir:" + dir);
                Directory.CreateDirectory(dir);
            }
        }
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        FileInfo fileInfo = new FileInfo(savePath);
        Stream stream = fileInfo.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }



    /// <summary>
    /// 解压文件
    /// </summary>
    private void CreateFileByZip(byte[] bytes, string savePath = null)
    {
        string path = Application.persistentDataPath + "/Res";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        FileInfo fileInfo = new FileInfo(savePath);
        Stream stream = fileInfo.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }


    /// <summary>
    /// 解压到沙河路径
    /// </summary>
    private void UnZip()
    {
        //Loger.Info("UnZip----");
        string savePath = Application.persistentDataPath + "/Res/Res.zip";
        string sourcePath = ApplicationPlatform.GetStreamingAssetsPath();// + "/Res";
        //Debug.Log(savePath);
        //Loger.Info("UnZip----savePath:" + savePath);
        if (Directory.Exists(Application.persistentDataPath + "/Res"))
        {
            IO.DeleteFiles(Application.persistentDataPath + "/Res");
        }
        DownLoadManager.DownLoad(sourcePath + "Res.zip", (www) =>
        {
            byte[] bytes = www.bytes;
            CreateFileByZip(bytes, savePath);
            Debug.Log(savePath);
            //FZipHelper.UnZip(savePath, Application.persistentDataPath + "/Res");
            IO.DeleteFiles(savePath);
            //StartGame();
        });
    }



    /// <summary>
    /// 比较版本号
    /// </summary>
    private void ComperVersion(string ver1, string ver2)
    {
        Debug.Log("v1:" + ver1);
        Debug.Log("v2:" + ver2);
        string[] strs1 = ver1.Split('.');
        string[] strs2 = ver2.Split('.');
        string data1 = strs1[0] + strs1[1] + strs1[2];
        string data2 = strs2[0] + strs2[1] + strs2[2];
        int v1 = int.Parse(data1);
        int v2 = int.Parse(data2);
        if (v2 > v1)
        {
            UnZip();
        }
        else
        {
            Debug.Log("Update file...");
            CheckLuaVersion();
        }
    }

    //public LoadAsset GetLoadAssetType()
    //{
    //    return _type;
    //}

    /// <summary>
    /// 检查版本号
    /// </summary>
    private void CheckVersion()
    {
        string ver1 = Application.persistentDataPath + "/Res/version.txt";
        string path = ApplicationPlatform.GetStreamingAssetsPath();
        string name = "version.txt";
        //Loger.Info("server:" + (path + name));
        //Loger.Info("ver1:" + ver1);
        if (File.Exists(ver1))
        {
            //Loger.Info("CheckVersion----> Exists:" + ver1);
            string data1 = DownLoadManager.LoadLocalTxt(ver1);
            DownLoadManager.DownLoad(path + name, (www) =>
            {
                string data2 = www.text;
                ComperVersion(data1, data2);
            });
        }
        else
        {
            //Loger.Info("CheckVersion----> not Exists:" + ver1);
            DownLoadManager.DownLoad(path + name, (www) =>
            {
                string data2 = www.text;
                UnZip();
                CreateFile(www.bytes, ver1);
            });
        }
    }
}
